<?php

namespace App\Console\Commands;

use App\Constant\JpushCode;
use App\Constant\NewFlowEnum;
use App\Events\JpushNoticeEvent;
use App\Events\LoanRequestRetryEvent;
use App\Events\NewFlowOrderEvent;
use App\Events\RiskResultEvent;
use App\Facades\MoneyPlatformRequestFacade;
use App\Facades\SamLogFacade;
use App\Models\LoanApply;
use App\Models\NewFlowOrder;
use App\Models\User;
use App\Models\UserApplyRiskLog;
use App\Models\UserCertOcr;
use App\Models\UserGlobal;
use App\Models\UserLoanRequest;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Matrix\Exception;

class SaveLoanCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'save:loan_request {action=exception|hold|checkException} {--status=} {--risk_status}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    protected function initAction()
    {
        $this->action = $this->argument('action');
        if (!in_array($this->action, ['exception','hold','checkException'])) {
            $this->error("error");
            exit();
        }
    }
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->initAction();
        $this->{$this->action}();
    }


    /**
     *
     */
    public function checkException() {
//        $loanModel = new UserLoanRequest();
//        $loanModel->setConnection('backend');
//
//        $riskModel = new UserApplyRiskLog();
//        $riskModel->setConnection('backend');
//
//        $maxLoan = $loanModel->where('updated_at', '<', Carbon::today()->addDay(-2))->orderBy('id', 'desc')->first();
//        $maxLoanId = $maxLoan->id;
//        $loan_request_ids = $riskModel->where('loan_request_id', '<', $maxLoanId)
//            ->where('updated_at', '>', Carbon::today()->addDay(-4))
//            ->where('updated_at', '<', Carbon::today()->addDay(-2))
//            ->pluck('loan_request_id')->toArray();
//        $loan_request_ids_sum_arr = array_chunk($loan_request_ids, 5000);
//        foreach ($loan_request_ids_sum_arr as $value){
//            $uids = $loanModel->where('risk_status', 4)->where('updated_at', '<', Carbon::today()->addDay(-2))
//                ->where('current', 1)->where('status', '<>', 7)
//                ->where('status', 9)->whereIn('id', $value)->pluck('user_id')->toArray();
//            if(count($uids) > 1){
//                $this->info('异常数据已修复count-'.count($uids));
//            }
//            UserGlobal::whereIn('uid', $uids)->update(['global_status' => 0]);
//        }
//
//        $loans  = $loanModel->where('risk_status', 4)->where('updated_at', '<', Carbon::today()->addDay(-2))
//            ->where('current', 1)->where('status', '<>', 7)
//            ->where('status', 9)->pluck('id')->toArray();
//        $risks = $riskModel->whereIn('loan_request_id', $loans)->get();
//        foreach ($risks as $risk){
//            event(new RiskResultEvent($risk));
//        }
    }


    public function hold()
    {
        /**
         * 风控拒绝 拉黑  1034379  1564862  1767235  2006430  2006711   2006754   2006803  2006916 2006955 2007004 2007040  2128644  2122377
         * 风控通过 授信表未更新 2006842 2006945 2006952  2038973 2006945
         * 重新进件 1491463  1784275
         *
         *
         */
         $lahei = [
             1034379, 1564862, 1767235, 2006430, 2006711, 2006754, 2006803, 2006916,2006842,2006952,
             2006955, 2007004, 2007040, 2128644, 2122377,  2006945, 2038973,
         ];
        $risks = UserApplyRiskLog::whereIn('loan_request_id', $lahei)->get();

        foreach ($risks as $risk){
            event(new RiskResultEvent($risk));
        }
        $chognxinjinjian = [1491463, 1784275];

        UserLoanRequest::whereIn('id', $chognxinjinjian)->update([
            'current' => 0
        ]);
        $uids =         UserLoanRequest::whereIn('id', $chognxinjinjian)->pluck('user_id')->toArray();
        UserGlobal::whereIn('uid', $uids)->update([
            'global_status' => 0
        ]);
        $this->info('done.');
    }

    public function exception(){
        $loans = UserLoanRequest::where('retry', 1)->
        where('retry_date', '>=', '2019-04-09 00:00:00')->get();
        DB::beginTransaction();
        try{
            foreach ($loans as $loan){
                    $loan->status = 4;
                    $loan->retry = 0;
                    $loan->retry_date = null;
                    $loan->status = 4;
                    $loan->failed_reason = '04-09~04-11授信超额置为失败';
                    $loan->failed_time = Carbon::now();
                    $loan->save();
                    $this->info($loan->id . "success");
                    //审核通过极光推送
//                    $jpush_id = UserGlobal::where('uid',$loan->user_id)->value('jpush_registration_id');
//                    if($jpush_id){
//                        $push_data = [
//                            'body'=>"抱歉，您的借款申请未能通过审批，点击了解详细信息",
//                            'title'=>"借款申请审批拒绝",
//                            'audience'=>JpushCode::AUDIENCE_TYPE_TWO,
//                            'to'=>[
//                                $jpush_id,
//                            ],
//                            'extras'=>[
//                                'jump_type'=>1,
//                            ],
//                        ];
//                        event(new JpushNoticeEvent($push_data));
//                    }
                    SamLogFacade::debug("04-09~04-11授信超额置为失败{$loan->user_id}授信申请【{$loan->id}】授信结果失败");
            }
            DB::commit();
        }catch (\Exception $exception){
            SamLogFacade::debug("04-09~04-11授信超额置为失败【{$loan->id}】更改失败状态失败");
            DB::rollBack();
        }
        $this->info('done');
    }



}
